<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场景名称" prop="sceneName">
        <el-input
          v-model="queryParams.sceneName"
          placeholder="请输入场景名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="场景类型" prop="sceneType">
        <el-select v-model="queryParams.sceneType" placeholder="请选择场景类型" clearable>
          <el-option label="自动" value="auto" />
          <el-option label="手动" value="manual" />
          <el-option label="定时" value="timer" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择是否启用" clearable>
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['environment:scene:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['environment:scene:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['environment:scene:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['environment:scene:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 场景卡片展示 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="6" v-for="scene in sceneList.slice(0, 4)" :key="scene.sceneId">
        <el-card class="scene-card" :class="{ 'scene-enabled': scene.isEnabled == '1' }">
          <div slot="header" class="clearfix">
            <span>{{ scene.sceneName }}</span>
            <el-switch
              v-model="scene.isEnabled"
              active-value="1"
              inactive-value="0"
              @change="handleSceneToggle(scene)"
              style="float: right; padding: 3px 0"
            ></el-switch>
          </div>
          <div class="scene-content">
            <div class="scene-icon">
              <i :class="scene.sceneIcon || 'el-icon-setting'" style="font-size: 32px;"></i>
            </div>
            <div class="scene-info">
              <p class="scene-type">{{ getSceneTypeLabel(scene.sceneType) }}</p>
              <p class="scene-desc">{{ scene.description || '暂无描述' }}</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="sceneList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场景ID" align="center" prop="sceneId" />
      <el-table-column label="场景名称" align="center" prop="sceneName" />
      <el-table-column label="家庭ID" align="center" prop="familyId" />
      <el-table-column label="场景类型" align="center" prop="sceneType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sceneType == 'auto'" type="success">自动</el-tag>
          <el-tag v-else-if="scope.row.sceneType == 'manual'" type="primary">手动</el-tag>
          <el-tag v-else-if="scope.row.sceneType == 'timer'" type="warning">定时</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="触发条件" align="center" prop="triggerCondition" :show-overflow-tooltip="true" />
      <el-table-column label="执行动作" align="center" prop="executeAction" :show-overflow-tooltip="true" />
      <el-table-column label="是否启用" align="center" prop="isEnabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnabled"
            active-value="1"
            inactive-value="0"
            @change="handleSceneToggle(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['environment:scene:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['environment:scene:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场景管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="场景名称" prop="sceneName">
              <el-input v-model="form.sceneName" placeholder="请输入场景名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家庭ID" prop="familyId">
              <el-input v-model="form.familyId" placeholder="请输入家庭ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="场景类型" prop="sceneType">
              <el-select v-model="form.sceneType" placeholder="请选择场景类型">
                <el-option label="自动" value="auto" />
                <el-option label="手动" value="manual" />
                <el-option label="定时" value="timer" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景图标" prop="sceneIcon">
              <el-input v-model="form.sceneIcon" placeholder="请输入场景图标类名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="触发条件" prop="triggerCondition">
          <el-input v-model="form.triggerCondition" type="textarea" placeholder="请输入触发条件（JSON格式）" />
        </el-form-item>
        <el-form-item label="执行动作" prop="executeAction">
          <el-input v-model="form.executeAction" type="textarea" placeholder="请输入执行动作（JSON格式）" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-radio-group v-model="form.isEnabled">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listScene, getScene, delScene, addScene, updateScene } from "@/api/environment/scene";

export default {
  name: "Scene",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场景管理表格数据
      sceneList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sceneName: null,
        sceneType: null,
        isEnabled: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sceneName: [
          { required: true, message: "场景名称不能为空", trigger: "blur" }
        ],
        familyId: [
          { required: true, message: "家庭ID不能为空", trigger: "blur" }
        ],
        sceneType: [
          { required: true, message: "场景类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询场景管理列表 */
    getList() {
      this.loading = true;
      listScene(this.queryParams).then(response => {
        this.sceneList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取场景类型标签
    getSceneTypeLabel(type) {
      const typeMap = {
        'auto': '自动',
        'manual': '手动',
        'timer': '定时'
      };
      return typeMap[type] || type;
    },
    // 场景启用/禁用切换
    handleSceneToggle(scene) {
      const text = scene.isEnabled === "1" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + scene.sceneName + '"场景吗？').then(function() {
        return updateScene(scene);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        scene.isEnabled = scene.isEnabled === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sceneId: null,
        sceneName: null,
        familyId: null,
        sceneType: null,
        description: null,
        sceneIcon: null,
        triggerCondition: null,
        executeAction: null,
        isEnabled: "1",
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sceneId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加场景管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sceneId = row.sceneId || this.ids
      getScene(sceneId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改场景管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sceneId != null) {
            updateScene(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScene(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sceneIds = row.sceneId || this.ids;
      this.$modal.confirm('是否确认删除场景管理编号为"' + sceneIds + '"的数据项？').then(function() {
        return delScene(sceneIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('environment/scene/export', {
        ...this.queryParams
      }, `scene_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.scene-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.scene-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.scene-enabled {
  border-color: #67c23a;
}
.scene-content {
  display: flex;
  align-items: center;
}
.scene-icon {
  margin-right: 15px;
  color: #409eff;
}
.scene-info {
  flex: 1;
}
.scene-type {
  margin: 0 0 5px 0;
  font-size: 12px;
  color: #909399;
}
.scene-desc {
  margin: 0;
  font-size: 14px;
  color: #606266;
}
</style>